const async = require('async');
const fs = require('fs');
const path = require('path');
class utils {
  seoResult(data = {}) {
    data = Object.assign(
      {
        description: '简介',
        keywords: '关键词',
        title: '标题',
      },
      data
    );
    const { title, description, keywords } = data;
    return { title, description, keywords };
  }
  result(data, code = 200, msg = '') {
    return { data, code, msg };
  }
  /**
   * 并发控制
   * @param {Array} list 传入进去的数组
   * @param {Number} limit 并发数量
   * @param {Function} callBack 回调
   */
  mapLimit(list, limit = 5, callBack) {
    return new Promise((resolve, reject) => {
      let currentCount = 0;
      async.mapLimit(
        list,
        limit,
        async (item) => {
          currentCount++;
          console.log(`目前并发量${currentCount}`);
          let data = await callBack(item);
          currentCount--;
          return data; // <- return a value!
        },
        (err, result) => {
          if (err) {
            reject(err);
          }
          resolve(result);
        }
      );
    });
  }
  /**
   * 遍历获取文件路径
   * @param {*} dir
   * @param {*} filesList
   */
  readFileList(dir, filesList = []) {
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
      const fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);
      if (stat.isDirectory()) {
        readFileList(path.join(dir, item), filesList); //递归读取文件
      } else {
        filesList.push(fullPath);
      }
    });
    return filesList;
  }
}
module.exports = new utils();
